// pages/device/device.js
Page({
  data: {
    deviceId: "",
    deviceKey: "", // 新增设备密钥字段
    deviceStatus: false,
    batteryLevel: 60,
    audioEffect: "普通",
    playMode: "顺序播放",
    networkState: "已连接",
    chargingState: "充电中",
    netDelay: 100,
    deviceToken: "",
    deviceInfo: null,
    "deviceState.power": false,
    "deviceState.batteryLevel": 0,
    "deviceState.charging": false,
    "deviceState.audioMode": "Sequential",
    "deviceState.audioEffect": "Common",
    "deviceState.wifiState": "Disconnected",
    lastUpdate: "",
    updating: false,
  },

  onLoad: function (options) {
    // 从路由参数获取设备ID和设备密钥
    if (options.id) {
      this.setData({
        deviceId: options.id,
        deviceKey: options.key || "", // 接收传递的设备密钥
      });

      // 直接获取设备状态，不进行鉴权
      this.getDeviceState(options.id);
    }
  },

  // 获取设备状态
  getDeviceState: function (deviceId) {
    const app = getApp();

    wx.request({
      url: "https://smartsound.top/api/v1/get/devicestate",
      method: "GET",
      data: {
        device_id: deviceId,
      },
      // 移除 Authorization header
      success: (res) => {
        if (res.data && res.data.code === 0) {
          // 更新设备状态数据
          this.setData({
            deviceStatus: res.data.Power.state === "ON",
            batteryLevel: res.data.Power.battery_level || 60,
            audioEffect: this.mapAudioEffect(res.data.Audio.effect),
            playMode: this.mapPlayMode(res.data.Audio.mode),
            networkState: this.mapNetworkState(res.data.Net.Wifi_state),
            chargingState: this.mapChargingState(res.data.Power.isCharging),
            netDelay: res.data.Net.net_delay || 100,
          });
        } else {
          wx.showToast({
            title: "获取设备状态失败",
            icon: "error",
            duration: 2000,
          });
        }
      },
      fail: (err) => {
        console.error("获取设备状态失败", err);
        wx.showToast({
          title: "网络错误",
          icon: "error",
          duration: 2000,
        });
      },
    });
  },

  // 映射音效模式
  mapAudioEffect: function (effect) {
    const effectMap = {
      Common: "普通",
      Rock: "摇滚",
      Jazz: "爵士",
      Classical: "古典",
    };
    return effectMap[effect] || "普通";
  },

  // 映射播放模式
  mapPlayMode: function (mode) {
    const modeMap = {
      Sequential: "顺序播放",
      Random: "随机播放",
      Shuffle: "洗牌播放",
    };
    return modeMap[mode] || "顺序播放";
  },

  // 映射网络状态
  mapNetworkState: function (state) {
    const stateMap = {
      Connected: "已连接",
      Disconnected: "未连接",
      Connecting: "连接中",
    };
    return stateMap[state] || "未知";
  },

  // 映射充电状态
  mapChargingState: function (state) {
    const stateMap = {
      Charging: "充电中",
      "Not Charging": "未充电",
      Full: "已充满",
    };
    return stateMap[state] || "未知";
  },

  // 获取设备详细信息
  fetchDeviceDetails: function (deviceId) {
    const app = getApp();
    const userInfo = wx.getStorageSync("userInfo");

    // 从本地存储中查找设备信息
    if (userInfo && userInfo.devices) {
      const device = userInfo.devices.find(
        (item) => item.device_id === deviceId
      );

      if (device) {
        this.setData({
          deviceStatus: device.status || false,
          batteryLevel: device.battery_level || 60,
          audioEffect: device.audio_effect || "播溪",
          playMode: device.audio_mode || "随机播放",
          networkState: device.network_state || "已连接",
          chargingState: device.charging_state || "充电中",
          netDelay: device.net_delay || 100,
        });
      }
    }
  },

  // 切换设备开关状态
  toggleDevice: function () {
    const { deviceId, deviceStatus } = this.data;
    const newStatus = !deviceStatus;

    this.setData({
      deviceStatus: newStatus,
    });

    // 更新设备状态到服务器
    this.updateDeviceStatus(deviceId, newStatus);
  },

  // 更新设备状态
  // 修改更新设备状态的方法，移除token验证
  updateDeviceStatus: function (deviceId, status) {
    const app = getApp();
    const userInfo = wx.getStorageSync("userInfo");

    // 更新本地存储中的设备状态
    if (userInfo && userInfo.devices) {
      const updatedDevices = userInfo.devices.map((item) => {
        if (item.device_id === deviceId) {
          return { ...item, status: status };
        }
        return item;
      });

      wx.setStorageSync("userInfo", {
        ...userInfo,
        devices: updatedDevices,
      });
    }

    // 构建请求数据
    const requestData = {
      user_id: userInfo ? userInfo.userId : 0,
      device_id: deviceId,
      Power_state: status ? "ON" : "OFF",
      Audio: {
        effect: this.reverseMapAudioEffect(this.data.audioEffect),
        mode: this.reverseMapPlayMode(this.data.playMode),
      },
    };

    // 发送请求到服务器
    wx.request({
      url: "https://smartsound.top/api/v1/change_state",
      method: "POST",
      data: requestData,
      success: (res) => {
        if (res.data && res.data.code === 0) {
          wx.showToast({
            title: status ? "设备已开启" : "设备已关闭",
            icon: "success",
            duration: 2000,
          });
        } else {
          wx.showToast({
            title: "操作失败",
            icon: "error",
            duration: 2000,
          });
          // 恢复原状态
          this.setData({
            deviceStatus: !status,
          });
        }
      },
      fail: (err) => {
        console.error("更新设备状态失败", err);
        wx.showToast({
          title: "网络错误",
          icon: "error",
          duration: 2000,
        });
        // 恢复原状态
        this.setData({
          deviceStatus: !status,
        });
      },
    });
  },

  // 添加反向映射函数
  reverseMapAudioEffect: function (effect) {
    const effectMap = {
      普通: "Common",
      摇滚: "Rock",
      爵士: "Jazz",
      古典: "Classical",
    };
    return effectMap[effect] || "Common";
  },

  // 反向映射播放模式
  reverseMapPlayMode: function (mode) {
    const modeMap = {
      顺序播放: "Sequential",
      随机播放: "Random",
      洗牌播放: "Shuffle",
    };
    return modeMap[mode] || "Sequential";
  },

  // 反向映射网络状态
  reverseMapNetworkState: function (state) {
    const stateMap = {
      已连接: "Connected",
      未连接: "Disconnected",
      连接中: "Connecting",
    };
    return stateMap[state] || "Disconnected";
  },

  // 反向映射充电状态
  reverseMapChargingState: function (state) {
    const stateMap = {
      充电中: "Charging",
      未充电: "Not Charging",
      已充满: "Full",
    };
    return stateMap[state] || "Not Charging";
  },

  // 更新设备设置
  // 4. 修改更新设备设置的方法，移除token验证
  updateDeviceSettings: function (settings) {
    const { deviceId } = this.data;
    const app = getApp();

    // 构建请求数据
    const timestamp = Date.now();
    const requestData = {
      device_id: deviceId,
      timestamp: timestamp,
      ...settings,
    };

    // 发送请求到服务器
    wx.request({
      url: `${app.globalData.apiBaseUrl}/device/settings`,
      method: "POST",
      // 移除 Authorization header
      data: requestData,
      success: (res) => {
        if (res.data && res.data.code === 0) {
          wx.showToast({
            title: "设置已更新",
            icon: "success",
            duration: 2000,
          });
        } else {
          wx.showToast({
            title: "设置失败",
            icon: "error",
            duration: 2000,
          });
        }
      },
      fail: (err) => {
        console.error("更新设备设置失败", err);
        wx.showToast({
          title: "网络错误",
          icon: "error",
          duration: 2000,
        });
      },
    });
  },

  // 设置音效模式
  setAudioEffect: function (e) {
    const mode = e.currentTarget.dataset.mode;
    this.setData({
      audioEffect: mode,
    });

    // 更新设备状态到服务器
    const { deviceId, deviceStatus } = this.data;

    // 构建请求数据
    const requestData = {
      device_id: deviceId,
      Power_state: deviceStatus ? "ON" : "OFF", // 添加当前设备电源状态
      Audio: {
        effect: this.reverseMapAudioEffect(mode),
        mode: this.reverseMapPlayMode(this.data.playMode),
      },
    };

    this.sendUpdateRequest(requestData, "音效模式已更新");
  },

  // 设置播放模式
  setPlayMode: function (e) {
    const mode = e.currentTarget.dataset.mode;
    this.setData({
      playMode: mode,
    });

    // 更新设备状态到服务器
    const { deviceId, deviceStatus } = this.data;

    // 构建请求数据
    const requestData = {
      device_id: deviceId,
      Power_state: deviceStatus ? "ON" : "OFF", // 添加当前设备电源状态
      Audio: {
        effect: this.reverseMapAudioEffect(this.data.audioEffect),
        mode: this.reverseMapPlayMode(mode),
      },
    };

    this.sendUpdateRequest(requestData, "播放模式已更新");
  },

  // 发送更新请求的通用方法
  sendUpdateRequest: function (requestData, successMessage) {
    const app = getApp();
    const userInfo = wx.getStorageSync("userInfo");

    // 更新请求数据格式
    const updatedRequestData = {
      user_id: userInfo ? userInfo.userId : 0,
      device_id: this.data.deviceId,
      Power_state:
        requestData.Power_state || (this.data.deviceStatus ? "ON" : "OFF"), // 确保始终有Power_state字段
      Audio: {
        effect: "Common",
        mode: "Sequential",
      },
    };

    // 发送请求到服务器
    wx.request({
      url: "https://smartsound.top/api/v1/change_state",
      method: "POST",
      data: updatedRequestData,
      success: (res) => {
        if (res.data && res.data.code === 0) {
          wx.showToast({
            title: successMessage,
            icon: "success",
            duration: 2000,
          });
        } else {
          wx.showToast({
            title: "操作失败",
            icon: "error",
            duration: 2000,
          });
        }
      },
      fail: (err) => {
        console.error("更新设备状态失败", err);
        wx.showToast({
          title: "网络错误",
          icon: "error",
          duration: 2000,
        });
      },
    });
  },

  // 返回上一页
  navigateBack: function () {
    wx.navigateBack();
  },

  // 加载设备信息
  loadDeviceInfo: function () {
    const app = getApp();
    const { device_id } = this.data;
    const userInfo = wx.getStorageSync("userInfo");
    const userId = userInfo ? userInfo.userId : 0;

    wx.request({
      url: `${app.globalData.deviceApiBaseUrl}/api/v1/get_device_info`, // 使用设备API基础URL和v1版本
      method: "GET",
      data: {
        device_id: device_id,
        user_id: userId,
      },
      success: (res) => {
        console.log("设备信息:", res.data);
        if (res.data && res.data.code === 0 && res.data.device) {
          const device = res.data.device;
          // 解析设备状态
          const powerState =
            device.status &&
            device.status.power &&
            device.status.power.state === "ON";
          const batteryLevel =
            device.status &&
            device.status.power &&
            device.status.power.battery_level
              ? device.status.power.battery_level
              : 0;
          const chargingState =
            device.status &&
            device.status.power &&
            device.status.power.charging_state
              ? device.status.power.charging_state
              : "NOT_CHARGING";
          const audioMode =
            device.status && device.status.audio && device.status.audio.mode
              ? device.status.audio.mode
              : "Sequential";
          const audioEffect =
            device.status && device.status.audio && device.status.audio.effect
              ? device.status.audio.effect
              : "Common";
          const wifiState =
            device.status &&
            device.status.network &&
            device.status.network.wifi_state
              ? device.status.network.wifi_state
              : "Disconnected";

          this.setData({
            deviceInfo: device,
            "deviceState.power": powerState,
            "deviceState.batteryLevel": batteryLevel,
            "deviceState.charging": chargingState === "CHARGING",
            "deviceState.audioMode": audioMode,
            "deviceState.audioEffect": audioEffect,
            "deviceState.wifiState": wifiState,
            lastUpdate: new Date().toLocaleTimeString(),
          });
        } else {
          wx.showToast({
            title: "获取设备信息失败",
            icon: "none",
          });
        }
      },
      fail: (err) => {
        console.error("获取设备信息请求失败", err);
        wx.showToast({
          title: "网络错误，请稍后重试",
          icon: "none",
        });
      },
      complete: () => {
        wx.hideLoading();
        this.setData({ loading: false });
      },
    });
  },

  // 更新设备状态
  updateDeviceState: function () {
    const { deviceState, device_id } = this.data;
    const app = getApp();
    const userInfo = wx.getStorageSync("userInfo");
    const userId = userInfo ? userInfo.userId : 0;

    // 显示加载提示
    this.setData({ updating: true });
    wx.showLoading({ title: "更新中..." });

    const requestData = {
      user_id: userId,
      device_id: device_id,
      Power_state: deviceState.power ? "ON" : "OFF",
      Audio: {
        mode: deviceState.audioMode,
        effect: deviceState.audioEffect,
      },
    };

    wx.request({
      url: `${app.globalData.deviceApiBaseUrl}/api/v1/change_state`, // 使用设备API基础URL
      method: "POST",
      data: requestData,
      success: (res) => {
        console.log("更新设备状态结果:", res.data);
        if (res.data && res.data.code === 0) {
          wx.showToast({
            title: "设备状态已更新",
            icon: "success",
          });
          // 更新最后更新时间
          this.setData({
            lastUpdate: new Date().toLocaleTimeString(),
          });
        } else {
          wx.showToast({
            title: "更新设备状态失败",
            icon: "none",
          });
        }
      },
      fail: (err) => {
        console.error("更新设备状态请求失败", err);
        wx.showToast({
          title: "网络错误，请稍后重试",
          icon: "none",
        });
      },
      complete: () => {
        wx.hideLoading();
        this.setData({ updating: false });
      },
    });
  },
});
